package cn.itcast.controller.system;

import cn.itcast.controller.BaseController;

import cn.itcast.domain.system.Dept;
import cn.itcast.service.system.DeptService;
import com.github.pagehelper.PageInfo;
import com.sun.xml.internal.bind.v2.TODO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/system/dept")//一级路径
public class DeptController extends BaseController {

    @Autowired
    private DeptService deptService;

    @RequestMapping(value = "/list",name = "查询所有部门")
    public String findAll( @RequestParam(name = "page",defaultValue = "1") Integer pageNum,
                           @RequestParam(name = "pageSize",defaultValue = "8") Integer pageSize){

        //使用PageHelper框架  写一个方法 参数 前端传过来的页数 和每一页显示条数  返回一个pageInfo
        PageInfo<Dept> pageInfo = deptService.findByPage(getCompanyId(), pageNum, pageSize);
        request.setAttribute("page",pageInfo);
        //int i=1/0;
        return "system/dept/dept-list";
    }

    @RequestMapping(value = "/toAdd",name = "添加部门")
    public String toAdd(String companyId){
        //查询出来当前企业的所有部门之后再跳转页面
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList",deptList);
        //直接转发到部门添加页面
       return "system/dept/dept-add";
    }

    @RequestMapping(value = "/edit",name = "保存部门")
    public String edit(Dept dept){
        if( dept.getParent().getId().equals("")){
            dept.getParent().setId(null);
        }
        //判断传递过来的参数是否有id的值   没有就保存save   有更新update
        if (StringUtils.isEmpty(dept.getId())) {
            String id = UUID.randomUUID().toString();
            dept.setId(id);

            dept.setCompanyId(getCompanyId());

            dept.setCompanyName(getCompanyName());

            deptService.save(dept);

        }else{

            deptService.update(dept);
        }

        //直接重定向到部门添加页面
        return "redirect:/system/dept/list.do";
    }


    @RequestMapping(value = "/toUpdate",name = "跳转到编辑页面（编辑和新增同一个页面）")
    public String toUpdate(String id){

        //数据回显
        Dept dept = deptService.findById(id);
        //查询出来当前企业的所有部门之后再跳转页面
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList",deptList);

        request.setAttribute("dept",dept);

        //直接转发到编辑页面
        return "system/dept/dept-add";
    }

    @RequestMapping(value = "/delete",name = "删除部门")
    public String delete(String id){

        deptService.deleteById(id);

        //直接转发到编辑页面
        return "redirect:/system/dept/list.do";
    }
}
